import express from 'express'
import multer from 'multer'
import fs from 'fs'
import Article from '../models/Article.js'

const router = express.Router()
const upload = multer({dest: './upload'})

const _handleResults = (results) => results.map(item => (
  {
    ...item,
    content: item.content.substring(0, 200) + '...'
  }
))

router.get('/', (req, res, next) => {
  if (req.query.offset) {
    Article.limit(req.query.offset, 5, (err, articles) => {
      if (err) return next(err)
      res.send(_handleResults(articles))
    })
  } else {
    Article.all((err, articles) => {
      if (err) return next(err)
      res.send(_handleResults(articles))
    })
  }
})
router.get('/byDate', (req, res, next) => {
  Article.allByDate((err, articles) => {
    if (err) return next(err)
    res.send(_handleResults(articles))
  })
})
router.post('/', upload.single('thumbnail'), (req,res,next) => {
  const formData = {
    title: req.body.title,
    content: req.body.content,
    category: req.body.category,
    thumbnail: req.file.filename
  }
  Article.create(formData, (err) => {
    if (err) return next(err)
    res.send({status: 'ok',message:"文章创建成功"})
  })
})

router.get('/:id', (req, res, next) => {
  Article.find(req.params.id, (err, articles) => {
    if (err) return next(err)
    res.send(articles[0])
  })
})

router.put('/:id', upload.none(), (req, res, next) => {
  const formData = {
    title: req.body.title,
    content: req.body.content,
    category: req.body.category,
    id: req.params.id
  }
  Article.update(formData, (err) => {
    if (err) return next(err)
    res.send({status: 'ok', message: '修改成功'})
  })
})

router.delete('/:id', (req, res, next) => {
  Article.find(req.params.id, (err, article) => {
    if (err) return next(err)
    fs.unlink('./upload/' + article[0].thumbnail, err => {
      if (err) return next(err)
      Article.remove(req.params.id, (err) => {
        if (err) return next(err)
        res.send({status: 'ok', message: '删除成功'})
      })
    })
  })
})

export default router